package com.mvc.core;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

/**
 * MVC框架的前端控制器
 * @author david
 *
 */
public class DispatcherServlet extends HttpServlet  {
	
	List<String> classNameList = new ArrayList<String>();//保存控制层组件的类名
	Properties properties = new Properties();
	HandlerMapping handlerMapping = new HandlerMapping();
	HandlerAdapter handlerAdapter = new HandlerAdapter();
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		loadConfig(config.getInitParameter("applicationContext"));	
		scanPackage(properties.getProperty("scanPackage"));
		
		//调用映射器
		handlerMapping.initIoc(classNameList);
		handlerMapping.initMappings(); //完成了对几个Map的填充
		handlerAdapter.setHandlerMapping(handlerMapping);  //两个类之间传递数据：要么是构造器，要么是set方法
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		
		String contextPath = request.getContextPath();
		String uri = request.getRequestURI();
		uri = uri.replace(contextPath, "");
		
		if(!handlerMapping.getUrlMethods().containsKey(uri)) {//判断请求的url是否在map中
			out.print("404 url not exist");
			return;
		}
		//封装请求参数，适配目标方法
		Object result = null;
		result  = handlerAdapter.adaptive(uri, request, response);
		
		String url = "";
		if(result instanceof ModelAndView) {
			ModelAndView model = (ModelAndView)result;
			url = model.getUrl();
			if(url!=null) {
				if(url.startsWith("redirect:")) {
					response.sendRedirect(request.getContextPath()+url.replace("redirect:", ""));
					return;
				} else {
					Map<String, Object> map = model.getMap();
					if(map!=null) {
						Set<String> keys = map.keySet();
						for(String key:keys) {
							request.setAttribute(key, map.get(key));
						}
					}
					request.getRequestDispatcher(model.getUrl()).forward(request, response);
				}
			}
		} else if(result instanceof String) {
			url = result.toString();
			if(url.startsWith("redirect:")) {
				response.sendRedirect(request.getContextPath()+url.replace("redirect:", ""));
				return;
			}
			request.getRequestDispatcher(url).forward(request, response);
		} else {
			//设置客户端拿到的数据类型是JSON对象，不加这行默认就是text/plain
			response.setContentType("text/json; charset=utf-8");
			String jsonString = JSON.toJSONString(result);
			out.print(jsonString);
		}
		
	}

	/**
	 * 加载全局应用配置文件,加载到Properties
	 * @param configFileName
	 */
	public void loadConfig(String configFileName) {
		InputStream is = this.getClass().getClassLoader().getResourceAsStream(configFileName);
		try {
			properties.load(is);
		} catch (IOException e) {
			System.out.println("500 load properties exception");
			e.printStackTrace();
		}	
	}
		
	/**
	 * 给定一个控制层组件的包名,读取所有的类名即文件名
	 * @param packageName
	 */
	public void scanPackage(String packageName) {
		URL url = this.getClass().getClassLoader().getResource(packageName.replace(".", "/"));
		File file = new File(url.getFile());
		File[] files = file.listFiles();
		if(files!=null) {
			if(files.length>0) {
				for(File f:files) {
					classNameList.add(packageName+"."+f.getName().replace(".class", ""));
				}
			}
		}
	}

}
